package com.lwc.auto;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenTemplate {
    @Autowired
    TokenProperties tokenProperties;
    /**
     * 生成token
     * @param payload  用户信息
     * @return  字符串
     */
    public String generateToken(Map<String,?> payload){
return JWT.create()
        .withHeader(getHeader()) //表头
        .withExpiresAt(getExpiresAt()) //有效时间
        .withPayload(payload)
        .sign(Algorithm.HMAC256(tokenProperties.getSecret()));
    }

    /**
     * 验证token
     * @param token
     * @return
     */

    public ValidResult ValidToken(String token){
        JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(tokenProperties.getSecret())).build();
        DecodedJWT decodedJWT =null;  //验证token   返回一个解密后的jwt


        try {
            decodedJWT = jwtVerifier.verify(token);
        } catch (JWTDecodeException e) {
            return new ValidResult(0,"token无效",null);
        }catch (TokenExpiredException e){
            return new ValidResult(0,"token已过期",null);
        }

        return  new ValidResult(1,"token有效",decodedJWT.getClaims());

    }


    /**
     * 头
     * @return
     */
    Map getHeader(){
        Map map=new HashMap<>();
        map.put("typ","jwt");
        map.put("alg","HMAC256");
        return map;
    }
    /**
     * 30分钟有效期
     * @return
     */
    Date getExpiresAt(){
        long time=System.currentTimeMillis()+ tokenProperties.getValidTime();
        Date  date=new Date(time);
        return  date;
    }


}
